const Router = require("@koa/router");
const axios = require("axios");
const jwt = require("jsonwebtoken");
const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
const { saveUserToDatabase } = require('./user');

const router = new Router({ prefix: "/auth" });

// 配置信息
const config = {
  googleClientId: process.env.GOOGLE_CLIENT_ID,
  googleClientSecret: process.env.GOOGLE_CLIENT_SECRET,
  jwtSecret: process.env.JWT_SECRET,
  redirectUri: process.env.GOOGLE_REDIRECT_URI
};

// 打印配置信息（隐藏敏感信息）
console.log(`${new Date().toLocaleString()} [CONFIG] Google OAuth配置:`, {
  googleClientId: config.googleClientId ? `${config.googleClientId.substring(0, 10)}...` : 'MISSING',
  googleClientSecret: config.googleClientSecret ? 'SET' : 'MISSING',
  jwtSecret: config.jwtSecret ? 'SET' : 'MISSING',
  redirectUri: config.redirectUri
});

// Google OAuth URL生成
router.get('/google', async (ctx) => {
  console.log(`${new Date().toLocaleString()} [AUTH] 开始生成Google OAuth URL`);
  
  const googleAuthUrl = 'https://accounts.google.com/o/oauth2/v2/auth';
  const params = new URLSearchParams({
    client_id: config.googleClientId,
    redirect_uri: config.redirectUri,
    response_type: 'code',
    scope: 'openid profile email',
    access_type: 'offline',
    state: 'random-state-string' // 建议使用随机生成的state参数增强安全性
  });
  
  const authUrl = `${googleAuthUrl}?${params.toString()}`;
  console.log(`${new Date().toLocaleString()} [AUTH] 生成的OAuth URL:`, authUrl);
  
  ctx.body = {
    success: true,
    authUrl: authUrl
  };
  
  console.log(`${new Date().toLocaleString()} [AUTH] Google OAuth URL生成成功`);
});

// 处理Google OAuth回调
router.post('/google/callback', async (ctx) => {
  console.log(`${new Date().toLocaleString()} [CALLBACK] 开始处理Google OAuth回调`);
  console.log(`${new Date().toLocaleString()} [CALLBACK] 请求体:`, ctx.request.body);
  console.log(`${new Date().toLocaleString()} [CALLBACK] 请求头:`, ctx.request.headers);
  
  try {
    const { code } = ctx.request.body;
    console.log(`${new Date().toLocaleString()} [CALLBACK] 提取的授权码:`, code ? `${code.substring(0, 20)}...` : 'MISSING');
    
    if (!code) {
      console.log(`${new Date().toLocaleString()} [CALLBACK] 错误: 缺少授权码`);
      ctx.status = 400;
      ctx.body = { success: false, error: 'Authorization code is required' };
      return;
    }

    // 用授权码换取访问令牌
    console.log(`${new Date().toLocaleString()} [TOKEN] 开始用授权码换取访问令牌`);
    const tokenRequestData = {
      client_id: config.googleClientId,
      client_secret: config.googleClientSecret,
      code: code,
      grant_type: 'authorization_code',
      redirect_uri: config.redirectUri
    };
    console.log(`${new Date().toLocaleString()} [TOKEN] 令牌请求参数:`, {
      ...tokenRequestData,
      client_secret: 'HIDDEN',
      code: `${code.substring(0, 20)}...`
    });
    
    const tokenResponse = await axios.post('https://oauth2.googleapis.com/token', tokenRequestData);
    console.log(`${new Date().toLocaleString()} [TOKEN] 令牌响应状态:`, tokenResponse.status);
    console.log(`${new Date().toLocaleString()} [TOKEN] 令牌响应数据:`, {
      ...tokenResponse.data,
      access_token: tokenResponse.data.access_token ? `${tokenResponse.data.access_token.substring(0, 20)}...` : 'MISSING'
    });

    const { access_token } = tokenResponse.data;
    if (!access_token) {
      throw new Error('未获取到访问令牌');
    }

    // 使用访问令牌获取用户信息
    console.log(`${new Date().toLocaleString()} [USER] 开始获取用户信息`);
    const userInfoUrl = `https://www.googleapis.com/oauth2/v2/userinfo?access_token=${access_token}`;
    console.log(`${new Date().toLocaleString()} [USER] 用户信息请求URL:`, userInfoUrl.replace(access_token, `${access_token.substring(0, 20)}...`));
    
    const userResponse = await axios.get(userInfoUrl);
    console.log(`${new Date().toLocaleString()} [USER] 用户信息响应状态:`, userResponse.status);
    console.log(`${new Date().toLocaleString()} [USER] 获取到的Google用户信息:`, userResponse.data);

    const googleUser = userResponse.data;
    if (!googleUser || !googleUser.email) {
      throw new Error('未获取到有效的用户信息');
    }

    // 将用户信息保存到数据库
    console.log(`${new Date().toLocaleString()} [DB] 开始保存用户信息到数据库`);
    const user = await saveUserToDatabase(googleUser);
    console.log(`${new Date().toLocaleString()} [DB] 用户保存成功:`, {
      id: user.id,
      email: user.email,
      nickname: user.nickname
    });

    // 生成JWT token
    console.log(`${new Date().toLocaleString()} [JWT] 开始生成JWT token`);
    const jwtPayload = {
      id: user.id,
      email: user.email,
      nickname: user.nickname,
      avatar: user.avatar
    };
    console.log(`${new Date().toLocaleString()} [JWT] JWT载荷:`, jwtPayload);
    
    const token = jwt.sign(jwtPayload, config.jwtSecret, { expiresIn: '7d' });
    console.log(`${new Date().toLocaleString()} [JWT] JWT token生成成功:`, `${token.substring(0, 30)}...`);

    const responseData = {
      success: true,
      token: token,
      user: {
        id: user.id,
        email: user.email,
        nickname: user.nickname,
        avatar: user.avatar
      }
    };
    
    console.log(`${new Date().toLocaleString()} [CALLBACK] 认证成功，返回响应:`, {
      ...responseData,
      token: `${token.substring(0, 30)}...`
    });
    
    ctx.body = responseData;

  } catch (error) {
    console.error(`${new Date().toLocaleString()} [ERROR] Google OAuth错误:`);
    console.error(`${new Date().toLocaleString()} [ERROR] 错误消息:`, error.message);
    console.error(`${new Date().toLocaleString()} [ERROR] 错误堆栈:`, error.stack);
    
    if (error.response) {
      console.error(`${new Date().toLocaleString()} [ERROR] HTTP响应状态:`, error.response.status);
      console.error(`${new Date().toLocaleString()} [ERROR] HTTP响应头:`, error.response.headers);
      console.error(`${new Date().toLocaleString()} [ERROR] HTTP响应数据:`, error.response.data);
    }
    
    if (error.request) {
      console.error(`${new Date().toLocaleString()} [ERROR] 请求配置:`, error.request);
    }
    
    ctx.status = 500;
    ctx.body = {
      success: false,
      error: 'Authentication failed',
      details: process.env.NODE_ENV === 'development' ? error.message : undefined
    };
  }
});

// 验证JWT token的中间件
const authenticateToken = async (ctx, next) => {
  console.log(`${new Date().toLocaleString()} [AUTH] 开始验证JWT token`);
  
  const authHeader = ctx.headers['authorization'];
  console.log(`${new Date().toLocaleString()} [AUTH] Authorization头:`, authHeader ? `${authHeader.substring(0, 30)}...` : 'MISSING');
  
  const token = authHeader && authHeader.split(' ')[1];
  console.log(`${new Date().toLocaleString()} [AUTH] 提取的token:`, token ? `${token.substring(0, 30)}...` : 'MISSING');

  if (!token) {
    console.log(`${new Date().toLocaleString()} [AUTH] 错误: 缺少访问令牌`);
    ctx.status = 401;
    ctx.body = { success: false, error: 'Access token required' };
    return;
  }

  try {
    const decoded = jwt.verify(token, config.jwtSecret);
    console.log(`${new Date().toLocaleString()} [AUTH] JWT验证成功，用户信息:`, {
      id: decoded.id,
      email: decoded.email,
      nickname: decoded.nickname
    });
    
    ctx.user = decoded;
    await next();
  } catch (error) {
    console.error(`${new Date().toLocaleString()} [AUTH] JWT验证失败:`, error.message);
    ctx.status = 403;
    ctx.body = { success: false, error: 'Invalid or expired token' };
  }
};

// 受保护的路由示例 - 获取用户信息
router.get('/profile', authenticateToken, async (ctx) => {
  console.log(`${new Date().toLocaleString()} [PROFILE] 获取用户资料，用户ID:`, ctx.user.id);
  
  ctx.body = {
    success: true,
    user: ctx.user
  };
  
  console.log(`${new Date().toLocaleString()} [PROFILE] 用户资料返回成功`);
});

// 登出路由
router.post('/logout', authenticateToken, async (ctx) => {
  console.log(`${new Date().toLocaleString()} [LOGOUT] 用户登出，用户ID:`, ctx.user.id);
  
  ctx.body = { success: true, message: 'Logged out successfully' };
  
  console.log(`${new Date().toLocaleString()} [LOGOUT] 登出成功`);
});

module.exports = { router, authenticateToken };